// index.js
const app = getApp()

Page({
  data: {
    userid: 0,
    // 是否在家
    atHome: 0,

    nowTime: 0,

    // 表数据
    meters: [
      // {
      //   name: "表名",
      //   meterId: 1,
      //   remainder: 0,
      //   image: app.globalData.ImgBackUrl + "/images/info/1.gif",
      //   prevCurrent: 2000, // 新增字段记录历史值
      //   current: 0,//动画变化值
      //   time: '03-11 08:22',
      // },
    ],

    // 综合结果
    meterResult: {
      userid: 0,
      state: "0",//状态
      value: "",
      time: "",
    },

    value: 'label_2',
    list: [
      { value: 'label_1', icon: `${app.globalData.ImgBackUrl}/images/info/xlicon1.png`, ariaLabel: '首页' },
      { value: 'label_2', icon: `${app.globalData.ImgBackUrl}/images/info/xlicon2.png`, ariaLabel: '设备' },
      { value: 'label_3', icon: `${app.globalData.ImgBackUrl}/images/info/xlicon3.png`, ariaLabel: '商品' },
    ],
  },

  onLoad() {
    let that = this
    console.log("onLoad");
    wx.hideTabBar()

    that.setData({
      userid: app.globalData.userid,
    })

    //用户是否在家
    that.getUserAtHome();
    // 创建动画实例
    that.initAnimations()
    // 获取各个表数据
    that.getServerData();
    // 获取综合结果
    that.getMeterResult();
  },

  //用户是否在家
  getUserAtHome() {
    let that = this

    wx.request({
      url: `${app.globalData.backUrl}we.aspx?ituid=${app.globalData.ituid}&itcid=10307&itjid=10307&userid=${that.data.userid}`,
      success(res) {
        that.setData({
          atHome: res.data.atHome
        })
      }
    })
  },

  // 获取综合结果
  getMeterResult() {
    let that = this

    wx.request({
      url: `${app.globalData.backUrl}we.aspx?ituid=${app.globalData.ituid}&itcid=10302&itjid=10302`,
      success(res) {
        that.setData({
          meterResult: res.data.meterResult
        })
      }
    })
  },

  // 跳转到表详情
  gotoMeterInfo(e) {
    wx.navigateTo({
      url: `/subPackages/show/pages/meterInfo/meterInfo?meterid=${e.currentTarget.dataset.meterid}&name=${e.currentTarget.dataset.name}`,
    })
  },

  onReady() {
    console.log("onReady");
  },

  onChange(e) {
    let that = this

    console.log("e.detail.value", e.detail.value);

    if (e.detail.value == "label_1") {
      wx.navigateTo({
        url: '/pages/new/new',
      })
    } else if (e.detail.value == "label_2") {

    } else if (e.detail.value == "label_3") {
      wx.navigateTo({
        url: '/subPackages/show/pages/goods/goods',
      })
    }
  },

  // 获取表数据
  getServerData() {
    let that = this

    wx.request({
      url: `${app.globalData.backUrl}we.aspx?ituid=${app.globalData.ituid}&itcid=10301&itjid=10301&userid=${that.data.userid}`,
      success(res) {
        that.updateMeters(res.data.meters)
      }
    })
  },

  // 更新表数据
  updateMeters(res) {
    let that = this

    const metersNew = res.map(item => {
      const currentTimestamp = Date.now();//当前时间戳

      const interfaceDate = new Date(item.time);
      const interfaceTimestamp = interfaceDate.getTime(); // 返回数据时间戳（毫秒）

      const difference = currentTimestamp - interfaceTimestamp;//时间戳的差值
      const isOver24h = difference > item.warningTime * 60 * 60 * 1000; // 是否超过24小时

      item.isOver24h = isOver24h;//新增是否超时的属性

      if (item.state == "1" && that.data.atHome == 1 && !isOver24h) {
        item.image = item.image + ".gif"
        return item
      } else {
        item.image = item.image + ".jpg"
        return item
      }
    })

    console.log("metersNew:", metersNew);

    // 首次获取数据
    if (that.data.meters.length == 0) {
      that.setData({
        meters: metersNew
      }, () => {
        that.data.meters.forEach((item, index) => {
          // 启动动画
          that.startAnimation(index, item.remainder)
        })
      })
    }
    // 非首次获取数据
    else {
      // 循环原数组
      that.data.meters.forEach((item, index) => {
        // 对比差异
        if (metersNew[index].remainder !== item.current) {
          // 保留历史值用于差值计算
          const mergedMeter = {
            ...item,
            prevCurrent: item.current // 记录动画起点
          }

          that.setData({
            [`meters[${index}]`]: mergedMeter
          }, () => {
            // 启动动画
            that.startAnimation(index, metersNew[index].remainder)
          })
        }
      })
    }
  },

  // 初始化动画实例
  initAnimations() {
    let that = this

  },

  // 启动数值变化动画
  startAnimation(index, remainder) {
    let that = this

    // 单个表
    const meter = that.data.meters[index]
    // 设置最大步数（比如最多变化60次，约1秒）
    const MAX_STEPS = 60

    const totalChange = remainder - meter.prevCurrent//本次所需总变化量
    const steps = Math.min(Math.abs(totalChange), MAX_STEPS)// 取较小值，最多变化60次

    // 强制每次变化数值stepVal为正负整数（向下取整），小于60次时每次变化1
    const stepVal = Math.sign(totalChange) * Math.floor(Math.abs(totalChange) / steps);
    // 计算未分配的差值
    // const remaining = totalChange - stepVal * steps;

    // 第几次（从0开始）
    let currentStep = 0
    // 计时器变化
    const timer = setInterval(() => {
      if (currentStep >= steps) {// 结束变化
        clearInterval(timer)

        // 修正剩余差值
        // meter.current += remaining;
        that.updateFinalState(index, remainder)
        return
      }

      // 增减变化
      meter.current += stepVal
      that.setData({
        [`meters[${index}]`]: {
          ...meter,
          current: meter.current,
          remainder: meter.current,
        }
      })
      currentStep++
    }, 32)// 约60/秒（2000ms/60≈32ms）
  },

  // 更新最终状态
  updateFinalState(index, updateRemainder) {
    let that = this


    // 单个表
    const meter = that.data.meters[index]

    that.setData({
      [`meters[${index}]`]: {
        ...meter,
        current: updateRemainder,
        remainder: updateRemainder,
        prevCurrent: updateRemainder
      }
    })
  },
})